import {
	Color,
	Cartographic,
	BoundingSphere,
	defined,
	Entity,
	ScreenSpaceEventHandler,
	Ellipsoid,
	LabelStyle,
	ScreenSpaceEventType,
	HorizontalOrigin,
	JulianDate,
	VerticalOrigin,
	Cartesian3,
	Math,
	Cartesian2
} from 'cesium';
import * as Cesium from 'cesium';
import { getImageUrl } from './base.ts';
const addGeojsonArea = (geoJsonFile, color, geojsondatasource, flag, callback) => {
	const promise = geojsondatasource.load(geoJsonFile, {
		stroke: Color.YELLOW, //多边形或线的颜色
		strokeWidth: 3, //多边形或线 宽度
		clampToGround: true //多边形或线 固定在地面上true/false
	});
	return promise.then(dataSource => {
		const neighborhoodsEntities = dataSource.entities.values;
		for (let i = 0; i < neighborhoodsEntities.length; i++) {
			let entity = neighborhoodsEntities[i];
			if (defined(entity.polygon)) {
				entity.polygon._id = entity.id;
				entity.polygon._name = entity.name;
				entity.polygon.outline = true; // 是否显示边界线
				entity.polygon.material = color;
				entity.polygon.height = 0; // 距地高度0米
				// entity.polygon.classificationType = ClassificationType.TERRAIN; //区块直接贴在地面上
				let polyPostions = entity.polygon.hierarchy.getValue(JulianDate.now()).positions; //从多边形上取出他的顶点
				let polyCenter = BoundingSphere.fromPoints(polyPostions).center; //通过顶点构建一个包围球
				polyCenter = Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter); //把包围球得中心做贴地得偏移
				entity.position = polyCenter;
				console.log(' text', entity, entity.name);
				entity.label = {
					//创建一个标签，在中心点位置
					text: entity.name,
					font: '16px sans-serif', // 字体大小
					style: LabelStyle.FILL_AND_OUTLINE, // 字体样式
					fillColor: Color.fromCssColorString('#fa0505'), // 字体填充色
					outlineWidth: 2, // 字体外圈线宽度（同样也有颜色可设置）
					outlineColor: Color.fromCssColorString('#fcfbfb'),
					showBackground: false,
					scale: 1,
					horizontalOrigin: HorizontalOrigin.CENTER,
					verticalOrigin: VerticalOrigin.BOTTOM,
					disableDepthTestDistance: Number.POSITIVE_INFINITY
					// distanceDisplayCondition: DistanceDisplayCondition(50.0,800000),
					// disableDepthTestDistance:100.0
				};

				if (neighborhoodsEntities.length == 1 && flag == 1 && entity.name != undefined) {
					let cartographic = Cartographic.fromCartesian(polyCenter);
					window.Viewer.camera.setView({
						destination: Cartesian3.fromDegrees(
							Math.toDegrees(cartographic.longitude),
							Math.toDegrees(cartographic.latitude),
							25000
						), // 设置位置
						orientation: {
							heading: Math.toRadians(20.0), // 方向
							pitch: Math.toRadians(-90.0), // 倾斜角度
							roll: 0
						}
					});
				}
			}
		}
		window.Viewer.dataSources.add(dataSource);
		if (flag === 0) {
			// 定义鼠标事件处理函数
			if (!window.handler) {
				startMouseMove();
			}
		} else if (flag === 1) {
			window.selectedGeojsonDataSources.entities.remove(window.tempObject);
			window.tempObject = undefined;
			window.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
		}

		return neighborhoodsEntities[0]._properties.id._value;
	});
};

const MouseFun = movement => {
	let highlightColor = Color.fromCssColorString('rgba(245,149,5,0.74)');
	let pickedObject = window.Viewer.scene.pick(movement.endPosition);
	console.log('move', pickedObject);
	// 判断是否有实体被选中 直接使用pickedObject.id.polygon
	if (defined(pickedObject) && pickedObject.id instanceof Entity && pickedObject.id.polygon) {
		let geometry = pickedObject.id.polygon.hierarchy;

		// height 是高程，必须加 否则不显示（一样的geometry）
		// 创建一个新实体来高亮选中的面
		let highlightEntity = new Entity({
			polygon: {
				hierarchy: geometry,
				height: 1, //必须加上才显示customdatasource，与在z上加10 不一样，那样不会高亮（不明白）？因为height是地球表面垂直高度，而xyz z是指向北极方向 不是高程
				material: highlightColor,
				outlineColor: highlightColor,
				outlineWidth: 10
			}
		});
		highlightEntity.name = pickedObject.id.name;

		if (window.tempObject != highlightEntity) {
			window.selectedGeojsonDataSources.entities.remove(window.tempObject);
			window.tempObject = highlightEntity;
			window.selectedGeojsonDataSources.entities.add(window.tempObject);
		}
	} else {
		window.selectedGeojsonDataSources.entities.remove(window.tempObject);
	}
};

const startMouseMove = () => {
	window.selectedGeojsonDataSources.entities.removeAll();
	window.tempObject = undefined;
	//移入高亮color

	if (!window.handler) {
		window.handler = new ScreenSpaceEventHandler(window.Viewer.canvas);
	}
	//console.log('geojson开启move事件');
	console.log(window.handler);
	window.handler.setInputAction(MouseFun, ScreenSpaceEventType.MOUSE_MOVE);
};
const addCunzhenPoint = (name, level, lon, lat, id) => {
	let image = null;
	let label = null;

	if (level == 0) {
		//村级
		image = getImageUrl('images/党组织.png');
		label = {
			text: name,
			font: '24px sans-serif', // 字体大小
			style: LabelStyle.FILL_AND_OUTLINE, // 字体样式
			fillColor: Color.fromCssColorString('#fc2601'), // 字体填充色
			outlineWidth: 2, // 字体外圈线宽度（同样也有颜色可设置）
			outlineColor: Color.fromCssColorString('#310c0c'),
			showBackground: false,
			horizontalOrigin: HorizontalOrigin.CENTER,
			scaleByDistance: new Cesium.NearFarScalar(5000, 1, 50000, 0.6), //视角近远影响文字扩大状态
			verticalOrigin: VerticalOrigin.BOTTOM,
			pixelOffset: new Cesium.Cartesian2(60, -20), //偏移量
			disableDepthTestDistance: Number.POSITIVE_INFINITY
		};
	} else if (level == 1) {
		//镇街道级
		image = getImageUrl('images/小红旗.png');
		label = {
			text: name,
			font: '24px sans-serif', // 字体大小
			style: LabelStyle.FILL_AND_OUTLINE, // 字体样式
			fillColor: Color.fromCssColorString('#fc2601'), // 字体填充色
			outlineWidth: 2, // 字体外圈线宽度（同样也有颜色可设置）
			outlineColor: Color.fromCssColorString('#310c0c'),
			showBackground: false,
			horizontalOrigin: HorizontalOrigin.CENTER,
			scaleByDistance: new Cesium.NearFarScalar(5000, 1, 50000, 0.6), //视角近远影响文字扩大状态
			verticalOrigin: VerticalOrigin.BOTTOM,
			pixelOffset: new Cesium.Cartesian2(60, -20), //偏移量
			disableDepthTestDistance: Number.POSITIVE_INFINITY
		};
	} else if (level == 2) {
		//县市级
		image = getImageUrl('images/五角星.png');
		label = {
			text: name,
			font: '20px sans-serif', // 字体大小
			style: LabelStyle.FILL_AND_OUTLINE, // 字体样式
			fillColor: Color.fromCssColorString('#f6b102'), // 字体填充色
			outlineWidth: 2, // 字体外圈线宽度（同样也有颜色可设置）
			outlineColor: Color.fromCssColorString('#310c0c'),
			showBackground: false,
			horizontalOrigin: HorizontalOrigin.CENTER,
			scaleByDistance: new Cesium.NearFarScalar(5000, 1, 50000, 0.8), //视角近远影响文字扩大状态
			verticalOrigin: VerticalOrigin.BOTTOM,
			pixelOffset: new Cesium.Cartesian2(75, 10), //偏移量
			disableDepthTestDistance: Number.POSITIVE_INFINITY
		};
	}
	let entity = window.Viewer.entities.add({
		poiId: id,
		name: name,
		position: Cartesian3.fromDegrees(lon, lat),
		billboard: {
			image: image, // 替换为你的图标路径
			scale: 0.8,
			scaleByDistance: new Cesium.NearFarScalar(5000, 1, 50000, 0.6) //视角近远影响文字扩大状态
		},
		label: label
	});
};

export { addGeojsonArea, startMouseMove, addCunzhenPoint };
